<template>
  <div class="login-container">
    <el-card class="login-box">
      <h2 class="login-title">用户管理系统</h2>
      <el-form
          :model="loginForm"
          :rules="rules"
          @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              clearable

          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <el-button
            type="primary"
            native-type="submit"
            :loading="loading"
            class="login-btn"

        >
          登录
        </el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import router from "@/router/router.js";

// 表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 验证规则
const rules = reactive({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' }
  ]
})

// 加载状态
const loading = ref(false)



const handleLogin = async () => {
  try {
    loading.value = true

    // 发送登录请求
    const response = await axios.post('http://localhost:8000/users/login/', {
      username: loginForm.username,
      password: loginForm.password
    })

    // 处理响应
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg)
      // 存储 token 和用户数据
      localStorage.setItem('auth_token', response.data.token)
      localStorage.setItem('user_info', JSON.stringify(response.data.username))
      await router.push('/')
    } else {
      ElMessage.error(response.data.msg || '登录失败')
    }
  } catch (error) {
    // 错误处理
    if (error.response) {
      const { data } = error.response
      ElMessage.error(data.msg || `请求错误：${error.response.status}`)
    } else {
      ElMessage.error('网络错误，请检查连接')
    }
  } finally {
    loading.value = false
  }
}

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100%;
  background: #f0f2f5;
}

.login-box {
  width: 400px;
  padding: 30px 25px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409EFF;
}

.login-btn {
  width: 100%;
  height: 40px;
  margin-top: 20px;
}

:deep(.el-input__wrapper) {
  height: 40px;
}
</style>